package com.CMS.client.datasource;

import java.util.List;

import com.CMS.client.PrivilegeTypeService;
import com.CMS.client.PrivilegeTypeServiceAsync;
import com.CMS.server.domain.PrivilegeType;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.smartgwt.client.data.DSRequest;
import com.smartgwt.client.data.DSResponse;
import com.smartgwt.client.data.Record;
import com.smartgwt.client.rpc.RPCResponse;

public class PrivilegeTypeDataSource extends BaseDataSource{
	
	public PrivilegeTypeDataSource(){
		super();
	}
	
	@Override
	protected void executeFetch(final String requestId, final DSRequest request,
			final DSResponse response) {
		
		PrivilegeTypeServiceAsync rpc = GWT.create(PrivilegeTypeService.class);
		rpc.fetch(new AsyncCallback<List<PrivilegeType>>() {
			
			@Override
			public void onSuccess(List<PrivilegeType> result) {
				final int startIndex = (request.getStartRow() < 0) ? 0 : request.getStartRow();
				final int endIndex = (request.getEndRow ()== null)? -1 : request.getEndRow();
				int size = result.size ();
                if (endIndex >= 0) {
                	if (endIndex < startIndex) {
                		size = 0;
                    }
                    else {
                        size = endIndex - startIndex + 1;
                    }
                }
                //Creamos los registros a devolver
				Record[] regs = new Record[result.size()];
				if (size > 0) {
					for (int i = 0; i < regs.length; i++) {
						Record record = new Record();
						copyValues(result.get(i), record);
						regs[i] = record;
					}
				}
				response.setData(regs);
				//IMPORTANTE: para que funcione el paginado debemos especificar
				//el total de registro del result set
				response.setTotalRows (result.size ());
				processResponse(requestId, response);
			}
			
			@Override
			public void onFailure(Throwable caught) {
				response.setStatus(RPCResponse.STATUS_FAILURE);
				processResponse(requestId, response);
			}
		});
	}

	@Override
	protected void executeAdd(String requestId, DSRequest request,
			DSResponse response) {
		// TODO Auto-generated method stub
		
	}

	@Override
	protected void executeUpdate(String requestId, DSRequest request,
			DSResponse response) {
		// TODO Auto-generated method stub
		
	}

	@Override
	protected void executeRemove(String requestId, DSRequest request,
			DSResponse response) {
		// TODO Auto-generated method stub
		
	}

	private void copyValues(PrivilegeType from, Record to) {
		to.setAttribute(getDescription(), from.getDescription());
		to.setAttribute(getId(), from.getId());
		to.setAttribute(getAddDate(), from.getAddDate());
		to.setAttribute(getModDate(), from.getModDate());
		to.setAttribute(getFlagDelete(), from.getFlagDelete());
	}
}
